<?php

namespace app\admin\controller;

use app\common\controller\AdminController;

//引入外部函数
use app\common\model\distribute\HandleRedMotherCommission;
use app\common\model\distribute\HandleVideoAuthCommission;
use app\common\model\hfztcy\LibAdminBalanceRecords;
use app\common\model\hfztcy\LibBalanceRecords;
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibOrder;
use app\common\model\hfztcy\LibOrderRedMother;
use app\common\model\hfztcy\LibOrderRefund;
use app\common\model\hfztcy\LibOrderVipAuth;
use app\common\model\LibAdmin;
use app\common\model\LibUser;
use common\Common;
use think\Db;
use think\Exception;


/**
 * 订单退款
 * @name Refund.php
 * @package hfztcy
 * @refund controller
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2020-6-5
 */
class Refund extends AdminController
{
    protected $model;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new LibOrderRefund();
        $this->rightVerify(session('admin'), url("admin/Login/login"));
        parent::__construct();
    }

    /**
     * Info: 红娘退款
     * Date: 2023/1/9 14:07
     */
    function agreeRefundByRedMother ()
    {
        $id = input('id', 0);
        $refundModel = new LibOrderRefund();
        $findRefundRes = $refundModel->findRefund(['id' => $id]);
        if ($findRefundRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'订单不存在',false));die();
        }

        if ($findRefundRes['data']['refund_state'] == 1) {
            echo json_encode(Common::errorArray(1, '订单已退款', ''));
            die();
        }

        $orderModel = new LibOrderRedMother();
        $findOrderRedMotherRes = $orderModel->findOrder(['user_id' => $findRefundRes['data']['user_id']]);
        if ($findOrderRedMotherRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'用户未支付红娘费用',false));die();
        }

        $model = new LibOrder();
        $findOrderRes = $model->findOrder(['id' => $findOrderRedMotherRes['data']['order_id']]);
        if ($findOrderRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'用户未支付红娘费用',false));die();
        }

        // 查询用户的上级
        $memberModel = new LibMember();
        $needClearUserByParentId = 0;// 需要移除的上级用户
        $userModel = new LibUser();
        $findUserRes = $userModel->findUser(['id' => $findRefundRes['data']['user_id']]);
        if ($findUserRes['errorCode'] == 0) {
            // 当前用户的直接推荐人
            $parent_id = $findUserRes['data']['parent_id'];
            $findMemberRes = $memberModel->findMember(['user_id' => $parent_id]);
            // 红娘身份是否平台赠送
            $is_platform_give = 0;//表示用户购买
            if ($findMemberRes['errorCode'] == 0) {//是红娘
                if (strpos($findMemberRes['data']['state'],'3') !== false && $findMemberRes['data']['is_platform_give']) {
                    $is_platform_give = $findMemberRes['data']['is_platform_give'];//表示用户推荐人中满足平台红娘数量，成为红娘
                }
            }
            if ($is_platform_give) {
                // 获取平台设置，推荐人中达到多少个红娘
                $configModel = new LibConfig();
                $findConfigRes = $configModel->findConfig(['item_key' => 'direct_red_mother_count']);
                $pay_red_mother_count = $findConfigRes['data']['item_value'];
                $sql = <<< SQL
SELECT count(*) num FROM `hfztcy_member_distribute` as a
left JOIN `base_user` as b on a.user_id = b.id
WHERE a.`pid` = {$parent_id} and FIND_IN_SET(3,identity)
SQL;
                $res = Db::query($sql);
                if ($res && $res[0]['num'] == $pay_red_mother_count) {
                    // 满足人数的用户集合
                    $sql = <<< SQL
SELECT b.id FROM `hfztcy_member_distribute` as a
left JOIN `base_user` as b on a.user_id = b.id
WHERE a.`pid` = {$parent_id} and FIND_IN_SET(3,identity) ORDER BY add_time DESC
SQL;
                    $res = Db::query($sql);
                    $ids = array_column($res,'id');
                    if (in_array($findRefundRes['data']['user_id'],$ids)) {
                        $needClearUserByParentId = $parent_id;
                    }
                }
            }
        }

        $transaction_id = $findOrderRes['data']['transaction_id'];
        $total_fee = $findOrderRes['data']['pay_amount'];
        $refund_fee = input('refund_fee',$total_fee);

        // 确认是否已退款
        require_once __DIR__ . "/../../../extend/pay/notify/lib/WxPay.Api.php";

        // 查询退款接口
        $queryInput = new \WxPayRefundQuery();
        $queryInput->SetTransaction_id($transaction_id);
        $queryResult = \WxPayApi::refundQuery($queryInput);
        if ($queryResult['result_code'] == 'SUCCESS' && $queryResult['return_code'] == 'SUCCESS') {
            echo json_encode(Common::errorArray(0, '订单已退款', false));
            die();
        }

        $refundModel = new LibOrderRefund();
        $refund_code = $findRefundRes['data']['code'];
        // 发起退款
        $input = new \WxPayRefund();
        $input->SetTransaction_id($transaction_id);//微信订单号
        $input->SetTotal_fee($total_fee * 100);
        $input->SetRefund_fee($refund_fee * 100);
        $input->SetOut_refund_no($refund_code);//设置退款单号
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        $refundResult = \WxPayApi::refund($input);

        Db::startTrans();
        try {
            $data = [];
            $data['refund_amount'] = $refund_fee;
            $data['refund_time'] = Common::getTime();//退款时间
            if ($refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS') {
                $data['error_info'] = $refundResult['return_msg'];
                $data['refund_state'] = 1;

                // 当前退款用户，移除红娘身份
                if ($findRefundRes['data']['user_id']) {
                    $sql = <<< SQL
SELECT identity FROM `base_user` WHERE `id` = {$findRefundRes['data']['user_id']}
SQL;
                    $userRes = Db::query($sql);
                    $identity = [];
                    if ($userRes) {
                        $identity = explode(',',$userRes[0]['identity']);
                    }
                    $identity = array_map('intval',$identity);
                    $identity = array_map(function ($val) use ($identity) {
                        if ($val == 3) {
                            unset($identity[$val]);
                        } else {
                            return $val;
                        }
                    },$identity);
                    $identity = array_filter($identity);
                    $identity = array_unique($identity);
                    if (empty($identity)) {
                        array_push($identity,1);
                    }
                    if ($identity) {
                        $identityStr = implode(',',$identity);
                        $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = {$findRefundRes['data']['user_id']}
SQL;
                        Db::execute($sql);

                        $sql = <<< SQL
UPDATE hfztcy_user 
SET state='{$identityStr}' 
WHERE `user_id` = {$findRefundRes['data']['user_id']}
SQL;
                        Db::execute($sql);
                    }
                }

                // 用户退款，如果其推荐人是通过分享，满足红娘人数而成为的红娘，则移除推荐人红娘身份。
                if ($needClearUserByParentId) {
                    $sql = <<< SQL
SELECT identity FROM `base_user` WHERE `id` = {$needClearUserByParentId}
SQL;
                    $userRes = Db::query($sql);
                    $identity = [];
                    if ($userRes) {
                        $identity = explode(',',$userRes[0]['identity']);
                    }
                    $identity = array_map('intval',$identity);
                    $identity = array_map(function ($val) use ($identity) {
                        if ($val == 3) {
                            unset($identity[$val]);
                        } else {
                            return $val;
                        }
                    },$identity);
                    $identity = array_filter($identity);
                    $identity = array_unique($identity);
                    if (empty($identity)) {
                        array_push($identity,1);
                    }
                    if ($identity) {
                        $identityStr = implode(',',$identity);
                        $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = '{$needClearUserByParentId}'
SQL;
                        Db::execute($sql);

                        $sql = <<< SQL
UPDATE hfztcy_user 
SET state='{$identityStr}',is_platform_give=0  
WHERE `user_id` = '{$needClearUserByParentId}'
SQL;
                        Db::execute($sql);
                    }
                }

                // 分润扣除，设置佣金记录状态
                $findOrderRes = $model->findOrder(['type' => 3,'user_id' => $findRefundRes['data']['user_id']]);
                if ($findOrderRes['errorCode'] == 0) {
                    $findOrderSubRes = $orderModel->findOrder(['order_id' => $findOrderRes['data']['id']]);
                    if ($findOrderSubRes['errorCode'] == 0) {
                        $adminModel = new LibAdmin();
                        $balanceRecordsModel = new LibBalanceRecords();
                        $adminBalanceRecordsModel = new LibAdminBalanceRecords();
                        $direct_user_id = $findOrderSubRes['data']['direct_user_id'];
                        $indirect_user_id = $findOrderSubRes['data']['indirect_user_id'];
                        $shi_admin_id = $findOrderSubRes['data']['shi_admin_id'];
                        $xian_admin_id = $findOrderSubRes['data']['xian_admin_id'];
                        $kf_admin_id = $findOrderSubRes['data']['kf_admin_id'];
                        $px_admin_id = $findOrderSubRes['data']['px_admin_id'];
                        $zt_commission_money = $findOrderSubRes['data']['zt_commission_money'];
                        $jt_commission_money = $findOrderSubRes['data']['jt_commission_money'];
                        $shi_commission_money = $findOrderSubRes['data']['shi_commission_money'];
                        $xian_commission_money = $findOrderSubRes['data']['xian_commission_money'];
                        $kf_commission_money = $findOrderSubRes['data']['kf_commission_money'];
                        $px_commission_money = $findOrderSubRes['data']['px_commission_money'];
                        // 直推红娘
                        if ($findOrderSubRes['data']['direct_user_id'])
                            HandleRedMotherCommission::updateDirectUserCommission(
                                $memberModel,
                                $userModel,
                                $balanceRecordsModel,
                                $direct_user_id,
                                $findOrderRes['data']['id'],
                                $zt_commission_money,
                                false);
                        // 间推红娘
                        if ($findOrderSubRes['data']['indirect_user_id'])
                            HandleRedMotherCommission::updateIndirectUserCommission(
                                $memberModel,
                                $userModel,
                                $balanceRecordsModel,
                                $indirect_user_id,
                                $findOrderRes['data']['id'],
                                $jt_commission_money,
                                false);
                        // 市代用户
                        if ($findOrderSubRes['data']['shi_admin_id'])
                            HandleRedMotherCommission::updateShiAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $shi_admin_id,
                                $findOrderRes['data']['id'],
                                $shi_commission_money,
                                false);
                        // 区县代用户
                        if ($findOrderSubRes['data']['xian_admin_id'])
                            HandleRedMotherCommission::updateXianAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $xian_admin_id,
                                $findOrderRes['data']['id'],
                                $xian_commission_money,
                                false);
                        // 客服部
                        if ($findOrderSubRes['data']['kf_admin_id'])
                            HandleRedMotherCommission::updateKfAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $kf_admin_id,
                                $findOrderRes['data']['id'],
                                $kf_commission_money,
                                false);
                        // 培训部
                        if ($findOrderSubRes['data']['px_admin_id'])
                            HandleRedMotherCommission::updatePxAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $px_admin_id,
                                $findOrderRes['data']['id'],
                                $px_commission_money,
                                false);

                        // 表示已执行
                        $model->updateOrder(['id' => $findOrderRes['data']['id']] , ['exec_state' => 1]);
                    }
                }
            } else {
                $data['refund_state'] = 2;
                $data['error_info'] = $refundResult['err_code_des'];
            }
            $refundModel->updateRefund(['id' => $findRefundRes['data']['id']], $data);
            Db::commit();

            echo json_encode(Common::errorArray(0, '退款成功', true));
            die();
        } catch (Exception $exception) {
            Db::rollback();
            if (isset($refundResult['return_msg']) && $refundResult['return_msg']) {
                echo json_encode(Common::errorArray(1, $refundResult['return_msg'], false));
                die();
            }
            echo json_encode(Common::errorArray(1, $exception->getMessage(), false));
            die();
        }
    }

    /**
     * Info: 栏目认证退款
     * Date: 2023/1/9 14:07
     */
    function agreeRefundByVideoAuth ()
    {
        $id = input('id', 0);
        $refundModel = new LibOrderRefund();
        $findRefundRes = $refundModel->findRefund(['id' => $id]);
        if ($findRefundRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'订单不存在',false));die();
        }

        if ($findRefundRes['data']['refund_state'] == 1) {
            echo json_encode(Common::errorArray(1, '订单已退款', ''));
            die();
        }

        $orderModel = new LibOrderVipAuth();
        $findOrderVipAuthRes = $orderModel->findOrder(['user_id' => $findRefundRes['data']['user_id']]);
        if ($findOrderVipAuthRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'用户未支付栏目认证费用',false));die();
        }

        $model = new LibOrder();
        $findOrderRes = $model->findOrder(['id' => $findOrderVipAuthRes['data']['order_id']]);
        if ($findOrderRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'用户未支付栏目认证费用',false));die();
        }

        $transaction_id = $findOrderRes['data']['transaction_id'];
        $total_fee = $findOrderRes['data']['pay_amount'];
        $refund_fee = input('refund_fee',$total_fee);

        // 确认是否已退款
        require_once __DIR__ . "/../../../extend/pay/notify/lib/WxPay.Api.php";

        // 查询退款接口
        $queryInput = new \WxPayRefundQuery();
        $queryInput->SetTransaction_id($transaction_id);
        $queryResult = \WxPayApi::refundQuery($queryInput);
        if ($queryResult['result_code'] == 'SUCCESS' && $queryResult['return_code'] == 'SUCCESS') {
            echo json_encode(Common::errorArray(0, '订单已退款', false));
            die();
        }

        $refundModel = new LibOrderRefund();
        $refund_code = $findRefundRes['data']['code'];
        // 发起退款
        $input = new \WxPayRefund();
        $input->SetTransaction_id($transaction_id);//微信订单号
        $input->SetTotal_fee($total_fee * 100);
        $input->SetRefund_fee($refund_fee * 100);
        $input->SetOut_refund_no($refund_code);//设置退款单号
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        $refundResult = \WxPayApi::refund($input);

        Db::startTrans();
        try {
            $data = [];
            $data['refund_amount'] = $refund_fee;
            $data['refund_time'] = Common::getTime();//退款时间
            if ($refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS') {
                $data['error_info'] = $refundResult['return_msg'];
                $data['refund_state'] = 1;

                // 更新用户栏目认证状态
                $memberModel = new LibMember();
                $memberModel->updateMember(['user_id' => $findRefundRes['data']['user_id']], ['is_vip_video' => 0]);

                // 分润扣除，设置佣金记录状态
                $findOrderRes = $model->findOrder(['type' => 2,'user_id' => $findRefundRes['data']['user_id']]);
                if ($findOrderRes['errorCode'] == 0) {
                    $findOrderSubRes = $orderModel->findOrder(['order_id' => $findOrderRes['data']['id']]);
                    if ($findOrderSubRes['errorCode'] == 0) {
                        $userModel = new LibUser();
                        $adminModel = new LibAdmin();
                        $balanceRecordsModel = new LibBalanceRecords();
                        $adminBalanceRecordsModel = new LibAdminBalanceRecords();
                        $direct_user_id = $findOrderSubRes['data']['direct_user_id'];
                        $indirect_user_id = $findOrderSubRes['data']['indirect_user_id'];
                        $shi_admin_id = $findOrderSubRes['data']['shi_admin_id'];
                        $xian_admin_id = $findOrderSubRes['data']['xian_admin_id'];
                        $kf_admin_id = $findOrderSubRes['data']['kf_admin_id'];
                        $px_admin_id = $findOrderSubRes['data']['px_admin_id'];
                        $store_user_id = $findOrderSubRes['data']['store_user_id'];
                        $store_parent_user_id = $findOrderSubRes['data']['store_parent_user_id'];
                        $zt_commission_money = $findOrderSubRes['data']['zt_commission_money'];
                        $jt_commission_money = $findOrderSubRes['data']['jt_commission_money'];
                        $shi_commission_money = $findOrderSubRes['data']['shi_commission_money'];
                        $xian_commission_money = $findOrderSubRes['data']['xian_commission_money'];
                        $kf_commission_money = $findOrderSubRes['data']['kf_commission_money'];
                        $px_commission_money = $findOrderSubRes['data']['px_commission_money'];
                        $md_commission_money = $findOrderSubRes['data']['md_commission_money'];
                        $md_give_red_mother_commission_money = $findOrderSubRes['data']['md_give_red_mother_commission_money'];
                        $store_parent_user_commission_money = $findOrderSubRes['data']['store_parent_user_commission_money'];
                        // 直推红娘
                        if ($findOrderSubRes['data']['direct_user_id'])
                            HandleVideoAuthCommission::updateDirectUserCommission(
                                $memberModel,
                                $userModel,
                                $balanceRecordsModel,
                                $direct_user_id,
                                $findOrderRes['data']['id'],
                                $zt_commission_money,
                                false);
                        // 间推红娘
                        if ($findOrderSubRes['data']['indirect_user_id'])
                            HandleVideoAuthCommission::updateIndirectUserCommission(
                                $memberModel,
                                $userModel,
                                $balanceRecordsModel,
                                $indirect_user_id,
                                $findOrderRes['data']['id'],
                                $jt_commission_money,
                                false);
                        // 市代用户
                        if ($findOrderSubRes['data']['shi_admin_id'])
                            HandleVideoAuthCommission::updateShiAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $shi_admin_id,
                                $findOrderRes['data']['id'],
                                $shi_commission_money,
                                false);
                        // 区县代用户
                        if ($findOrderSubRes['data']['xian_admin_id'])
                            HandleVideoAuthCommission::updateXianAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $xian_admin_id,
                                $findOrderRes['data']['id'],
                                $xian_commission_money,
                                false);
                        // 客服部
                        if ($findOrderSubRes['data']['kf_admin_id'])
                            HandleVideoAuthCommission::updateKfAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $kf_admin_id,
                                $findOrderRes['data']['id'],
                                $kf_commission_money,
                                false);
                        // 培训部
                        if ($findOrderSubRes['data']['px_admin_id'])
                            HandleVideoAuthCommission::updatePxAdminCommission(
                                $adminModel,
                                $adminBalanceRecordsModel,
                                $px_admin_id,
                                $findOrderRes['data']['id'],
                                $px_commission_money,
                                false);
                        // 门店用户
                        if ($findOrderSubRes['data']['store_user_id']) {
                            $store_commission_money = $md_commission_money + $md_give_red_mother_commission_money;
                            HandleVideoAuthCommission::updateStoreUserCommission(
                                $memberModel,
                                $userModel,
                                $balanceRecordsModel,
                                $store_user_id,
                                $findOrderRes['data']['id'],
                                $store_commission_money,
                                false);
                        }
                        // 门店上级用户
                        if ($findOrderSubRes['data']['store_parent_user_id'])
                            HandleVideoAuthCommission::updateStoreParentUserCommission(
                                $memberModel,
                                $userModel,
                                $balanceRecordsModel,
                                $store_parent_user_id,
                                $findOrderRes['data']['id'],
                                $store_parent_user_commission_money,
                                false);

                        // 表示已执行
                        $model->updateOrder(['id' => $findOrderRes['data']['id']] , ['exec_state' => 1]);
                    }
                }
            } else {
                $data['refund_state'] = 2;
                $data['error_info'] = $refundResult['err_code_des'];
            }
            $refundModel->updateRefund(['id' => $findRefundRes['data']['id']], $data);
            Db::commit();

            echo json_encode(Common::errorArray(0, '退款成功', true));
            die();
        } catch (Exception $exception) {
            Db::rollback();
            if (isset($refundResult['return_msg']) && $refundResult['return_msg']) {
                echo json_encode(Common::errorArray(1, $refundResult['return_msg'], false));
                die();
            }
            echo json_encode(Common::errorArray(1, $exception->getMessage(), false));
            die();
        }
    }

    /**
     * Info: 退款审核
     * Date: 2023/1/9 14:07
     */
    function auditStatus ()
    {
        $id = input('id', 0);
        $status = input("state");
        $refundModel = new LibOrderRefund();
        $findRefundRes = $refundModel->findRefund(['id' => $id]);
        if ($findRefundRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'订单不存在',false));die();
        }

        if ($findRefundRes['data']['audit_state'] > 0) {
            echo json_encode(Common::errorArray(1, '已审核', ''));
            die();
        }

        Db::startTrans();
        try {
            if ($status == 1) {
                $reason = '审核成功';
            } else {
                $reason = input("reason");
            }
            $data['audit_state'] = $status;
            $data['audit_msg'] = $reason;
            $data['audit_time'] = Common::getTime();

            $refundModel->updateRefund(['id' => $id], $data);
            $code = 0;
            $msg = "更新成功";
            $flag = true;
            Db::commit();
        } catch (Exception $exception) {
            $code = 1;
            $msg = "更新失败" . $exception->getMessage();
            $flag = false;
            Db::rollback();
        }
        echo json_encode(Common::errorArray($code, $msg, $flag));
        die();
    }
}

?>